<template>
  <div class="news-types" v-if="channels.length > 0">
    <div
      class="item"
      v-for="item  in showChannels"
      :key="item.channelId"
      :class="{active: item.channelId === chooseId,}"
        @click="switchTo(item.channelId)"
    >
      <span class="name">{{item.name}}</span>
    </div>
    <a href @click.prevent="iscoll=!iscoll">{{iscoll? "展开":"收起"}}</a>
    <!-- 上边.prevent 是a标签的阻止事件的默认行为， -->
  </div>
</template>

<script>
import { getNewsChannels } from "@/service/newsService";
export default {
  data() {
    return {
      channels: [],
      iscoll: true, //当前是否为折叠状态
      chooseId: null, //当前选中的频道id
    };
  },

  computed: {
    showChannels() {
      if (this.iscoll) {
        return this.channels.slice(0, 8);
      } else {
        return this.channels;
      } //展开和折叠状态
    },
  },

  async created() {
    var res = await getNewsChannels();
    console.log(res);
    this.channels = res;
    //此时才有频道
    // this.chooseId = this.channels[0].channelId;
    this.switchTo(this.channels[0].channelId)
  },

  methods:{
    switchTo(id){
      this.chooseId=id;
      this.$emit("change",this.chooseId)    //非常重要，这里触发，
    }
  }


};
</script>

<style scoped>
.news-types {
  margin: 30px 0;
  border-bottom: 1px solid #ccc;
  display: flex;
  flex-wrap: wrap;
  font-size: 14px;
  padding-bottom: 15px;
}
.item {
  padding: 10px 20px;
  border-radius: 5px;
  border: 1px solid #ccc;
  margin-right: 15px;
  margin: 7px 15px 7px 0;
  cursor: pointer;
  position: relative;
}
.item:hover {
  background: #ccc;
}
.active {
  background: #000;
  color: #fff;
}
.news-types a {
  align-self: flex-end;
  margin-bottom: 20px;
  color: #409eff;
}
</style>